import { login } from '@/apis/user'
import { TOKEN_KEY } from '@/constants/KEY'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => {
    return {
      // 优先从本地取
      token: getToken() || ''
    }
  },
  mutations: {
    setToken(state, newtoken) {
      state.token = newtoken
      // 本地存一份
      setToken(newtoken)
    },
    clearUserInfo(state) {
      // 清除Token
      state.token = ''
      removeToken(TOKEN_KEY)
    }
  },
  actions: {
    async doLogin(ctx, { username, password }) {
      // 1.调用接口
      const res = await login({ username, password })
      // 2. 提交mutation
      ctx.commit('setToken', res.data.token)
    }
  }
}
